﻿using czj_shop.Models.Database;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace czj_shop.Service
{
    public class CarService/*:ICarService*/
    {
        private readonly czj_shopContext _db;
        /// <summary>
        /// 购物车服务构造函数
        /// </summary>
        /// <param name="db"></param>
        public CarService(czj_shopContext db)
        {
            _db = db;
        }
        /// <summary>
        /// 根据用户Id和商品Id查询购物车对象
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="goodId"></param>
        /// <returns></returns>
        public Car GetCar(int userId, int goodId)
        {

            return _db.Cars.FirstOrDefault(x => x.Uid == userId && x.GoodId == goodId);
        }
        /// <summary>
        /// 更新购物车商品数量
        /// </summary>
        /// <param name="car"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public bool UpdateCarCount(Car car, int count)
        {
            //                       int +/-
            car.Count = car.Count + count;
            _db.Cars.Update(car);
            return _db.SaveChanges() > 0 ? true : false;
        }
        /// <summary>
        /// 根据商品Id和用户Id添加购物车记录
        /// </summary>
        /// <param name="goodId"></param>
        /// <param name="uId"></param>
        /// <returns></returns>
        public bool AddCar(int goodId, int userId)
        {
            var good = _db.Goods.FirstOrDefault(x => x.GoodId == goodId);
            if (good == null)
                return false;

            var car = new Car
            {
                Uid = userId,
                GoodId = goodId,
                Count = 1,
                CreateTime = DateTime.Now,
                GoodCover = good.GoodCover,
                GoodName = good.GoodName,
                Price = good.Price
            };
            _db.Cars.Add(car);
            return _db.SaveChanges() > 0 ? true : false;
        }
        /// <summary>
        /// 删除购物车
        /// </summary>
        /// <returns></returns>
        public bool DeleteCar(Car car)
        {
            _db.Cars.Remove(car);
            return _db.SaveChanges() > 0 ? true : false;
        }
    }
}
